import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Select, message, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { workspaceAPI } from '../../api/workspace';
import type { WorkspaceMember, User } from '../../types/api';
import type { DefaultOptionType } from 'antd/es/select';

interface WorkspaceMemberListProps {
  workspaceId: string;
}

export const WorkspaceMemberList: React.FC<WorkspaceMemberListProps> = ({ workspaceId }) => {
  const [members, setMembers] = useState<WorkspaceMember[]>([]);
  const [availableUsers, setAvailableUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingMember, setEditingMember] = useState<WorkspaceMember | null>(null);
  const [form] = Form.useForm();

  // 加载成员列表
  const loadMembers = async () => {
    if (!workspaceId) return;
    setLoading(true);
    try {
      const response = await workspaceAPI.getWorkspaceMembers(workspaceId);
      if (response.success && Array.isArray(response.data)) {
        setMembers(response.data);
      }
    } catch (error) {
      console.error('加载成员失败:', error);
      message.error('加载成员失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载可添加的用户列表
  const loadAvailableUsers = async () => {
    if (!workspaceId) return;
    setLoadingUsers(true);
    try {
      const response = await workspaceAPI.getAvailableUsers(workspaceId);
      if (response.success && Array.isArray(response.data)) {
        setAvailableUsers(response.data);
      }
    } catch (error) {
      console.error('加载用户列表失败:', error);
      message.error('加载用户列表失败');
    } finally {
      setLoadingUsers(false);
    }
  };

  useEffect(() => {
    loadMembers();
  }, [workspaceId]);

  useEffect(() => {
    if (modalVisible && !editingMember) {
      loadAvailableUsers();
    }
  }, [modalVisible, editingMember]);

  // 添加或更新成员
  const handleSubmit = async (values: any) => {
    try {
      if (editingMember) {
        // 更新成员角色
        const response = await workspaceAPI.updateWorkspaceMember(
          workspaceId,
          editingMember.id,
          values
        );
        if (response.success) {
          message.success('成员角色更新成功');
          loadMembers();
        }
      } else {
        // 添加新成员
        const response = await workspaceAPI.addWorkspaceMember(workspaceId, values);
        if (response.success) {
          message.success('成员添加成功');
          loadMembers();
        }
      }
      setModalVisible(false);
      form.resetFields();
      setEditingMember(null);
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  // 移除成员
  const handleRemove = async (memberId: string) => {
    try {
      const response = await workspaceAPI.removeWorkspaceMember(workspaceId, memberId);
      if (response.success) {
        message.success('成员移除成功');
        loadMembers();
      }
    } catch (error) {
      console.error('移除失败:', error);
      message.error('移除失败');
    }
  };

  const columns = [
    {
      title: '用户名',
      dataIndex: ['user', 'username'],
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: ['user', 'email'],
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
    },
    {
      title: '加入时间',
      dataIndex: 'joinedAt',
      key: 'joinedAt',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: WorkspaceMember) => (
        <div className="space-x-2">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => {
              setEditingMember(record);
              form.setFieldsValue(record);
              setModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要移除该成员吗？"
            onConfirm={() => handleRemove(record.id)}
            okText="确定"
            cancelText="取消"
            okButtonProps={{ type: 'primary', style: { backgroundColor: '#1890ff' } }}
          >
            <Button type="text" danger icon={<DeleteOutlined />}>
              移除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  return (
    <div>
      <div className="mb-4">
        <Button
          type="primary"
          size="large"
          icon={<PlusOutlined />}
          style={{ backgroundColor: '#1890ff', height: '40px', fontSize: '16px' }}
          onClick={() => {
            setEditingMember(null);
            form.resetFields();
            setModalVisible(true);
          }}
        >
          添加成员
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={members}
        rowKey="id"
        loading={loading}
      />

      <Modal
        title={editingMember ? '编辑成员角色' : '添加成员'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingMember(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        okText="确定"
        cancelText="取消"
        okButtonProps={{ type: 'primary', style: { backgroundColor: '#1890ff' } }}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          {!editingMember && (
            <Form.Item
              name="userId"
              label="选择用户"
              rules={[{ required: true, message: '请选择用户' }]}
            >
              <Select
                placeholder="请选择用户"
                showSearch
                loading={loadingUsers}
                filterOption={(input: string, option: DefaultOptionType | undefined) =>
                  (option?.label?.toString() || '').toLowerCase().includes(input.toLowerCase())
                }
                options={availableUsers.map(user => ({
                  label: `${user.username} (${user.email})`,
                  value: user.id
                }))}
              />
            </Form.Item>
          )}
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              placeholder="请选择角色"
              options={[
                { label: '管理员', value: 'admin' },
                { label: '成员', value: 'member' },
                { label: '访客', value: 'guest' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}; 